package top.lunarye.handler;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.exceptions.StatefulException;
import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.lang.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import top.lunarye.annotation.TokenToStaff;
import top.lunarye.modules.staff.entity.Staff;
import top.lunarye.modules.staff.service.IStaffService;
import top.lunarye.modules.staff.service.impl.StaffServiceImpl;
import top.lunarye.utils.RestResponse;
import top.lunarye.utils.SystemCode;

/**
 * @description:
 * @author: lunar
 * @since: 2021-07-19
 */
@Component
public class TokenToStaffMethodArgumentResolver implements HandlerMethodArgumentResolver {

    public TokenToStaffMethodArgumentResolver() {
    }

    @Autowired
    private StaffServiceImpl staffService;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        if (methodParameter.hasParameterAnnotation(TokenToStaff.class)) {
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws UtilException{
        Staff staff = null;
        if (methodParameter.hasParameterAnnotation(TokenToStaff.class)) {
            String token = nativeWebRequest.getHeader("token");
            if (null != token && !"".equals(token)) {
                Object loginId = StpUtil.getLoginIdByToken(token);
                if (loginId == null) {
                    throw new StatefulException(400, "token无效");
                }
                String username = (String) loginId;
                staff = staffService.selectStaffByUsername(username);
                if (staff.getIsDisable() == 1) {
                    throw new UtilException("账号已被封禁，请联系管理员");
                }
            } else {
                throw new StatefulException(400, "token无效");
            }
        }
        return staff;
    }
}
